package cfig.launcher

import cfig.helper.Helper
import cfig.helper.ZipHelper
import cfig.ota.Payload
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import kotlin.system.exitProcess

class Unpacker {
    companion object {
        val log: Logger = LoggerFactory.getLogger(Unpacker::class.java)
        fun main(args: Array<String>) {
            val outDir = Helper.prop("workDir")
            File(outDir).let {
                if (it.exists()) {
                    log.info("Removing $outDir")
                    it.deleteRecursively()
                }
                log.info("Creating ${it.path}")
                it.mkdirs()
            }
            val otaFile = args[0]
            if (otaFile.endsWith(".zip")) {
                ZipHelper.unzip(otaFile, outDir)
                if (File("$outDir/payload.bin").exists()) {
                    log.info("Continue to unpack " + File("$outDir/payload.bin").name + "...")
                    Payload.parse("$outDir/payload.bin").let { pl ->
                        pl.setUp()
                        pl.printInfo()
                        pl.unpack()
                    }
                }
            } else if (otaFile.endsWith(".bin")) {
                Payload.parse(otaFile).let { pl ->
                    pl.setUp()
                    pl.printInfo()
                    pl.unpack()
                }
            } else {
                log.error("unrecognized file: $otaFile")
                exitProcess(1)
            }
            log.info("Done")
        }
    }

}
